import path from 'path';
import fs from 'fs';
import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getSecondHand, getIdSecondHand, createSecondHand, updateSecondHand, deleteSecondHand, secondHandStatusChange, createFile, findFileById, deleteFileById, byKeyWordSelect } from './secondHand.service';
import { getFavorite } from '../favorites/favorites.service';
import { cornerDestroyById } from '../corner/common.service';
import { createNotice } from '../notification/notification.service';
import { createUserAuth, reduceSendAuth, selectUserAuth } from '../user_auth/user_auth.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status
  let pageNo = request.query.pageNo

  let user = request.user;
  let currentUser = request.query.currentUser;
  const uid = request.query.userId;
  let userId = uid ? parseInt(`${uid}`, 10) : 0;
  if (user && user.id > 0 && currentUser) {
    userId = user.id;
  } else if (!user && currentUser) {
    response.send({ data: {} })
    return;
  }

  const data = await getSecondHand(parseInt(`${status}`, 10), 10, parseInt(`${pageNo}`, 10), userId);
  for (const item of data.data as any) {
    if ("image_id" in item && item.image_id > 0) {
      const imgData = await findFileById(item.image_id, 0, 0, 'medium')
      item.cover = imgData[0];
    }
  }

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const secondHandDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdSecondHand(parseInt(postId, 10));
    
    const user = request.user;
    if (user && user.id > 0) {
      let favoriteParam = { user_id: user.id, type: 6, target_id: data.id }
      let favorite = await getFavorite(favoriteParam);
      data.favorite = (favorite as any).length > 0 ? favorite[0] : null;
    }

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 按关键词查询（模糊查询）
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  const { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let secondhand = request.body;

  secondhand.status = 0;
  let user = request.user;
  if (user.type != 1) {
    secondhand.user_id = user.id
  }

  // 初次发布添加免费发布权限
  let isUserAuthId = await selectUserAuth(user.id);
  if (Object.keys(isUserAuthId).length !== 0 && isUserAuthId[0].user_id && isUserAuthId[0].user_id > 0) {
    if (isUserAuthId[0].send_info_count && isUserAuthId[0].send_info_count > 0) {
      // 减少发布信息权限
      await reduceSendAuth(isUserAuthId[0].user_id);

      // 创建内容
      if (secondhand.id && secondhand.id > 0) {
        let image_id = secondhand.image_id
        let img = await findFileById(image_id, 0, 0);
        if (!img || img.length === 0) {
          let imgs = await findFileById(0, secondhand.id, 6);
          if (imgs && imgs.length > 0) {
            secondhand.image_id = imgs[imgs.length - 1].id
          }
        }
        const data = await updateSecondHand(secondhand, parseInt(secondhand.id, 10));
        response.send(data);
      } else {
        const data = await createSecondHand(secondhand);
        response.send(data);
      }
    } else {
      response.send({
        msg: '免费发布权限已经用光了！请购买后发布。',
        status: 411
      });
    }

    return;
  } else {
    // 写入免费权限
    let post = { 'user_id': user.id }
    await createUserAuth(post);

    // 创建内容
    if (secondhand.id && secondhand.id > 0) {
      let image_id = secondhand.image_id
      let img = await findFileById(image_id, 0, 0);
      if (!img || img.length === 0) {
        let imgs = await findFileById(0, secondhand.id, 6);
        if (imgs && imgs.length > 0) {
          secondhand.image_id = imgs[imgs.length - 1].id
        }
      }
      const data = await updateSecondHand(secondhand, parseInt(secondhand.id, 10));
      response.send(data);
    } else {
      const data = await createSecondHand(secondhand);

      // 减少发布信息权限
      await reduceSendAuth(user.id);
      response.send(data);
    }
  }
};

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取内容
  const post = _.pick(request.body, [
    'status',
    'remark_zh',
    'remark_ug',
    'name_zh',
    'name_ug',
    'price',
    'lectureRange_zh',
    'lectureRange_ug',
    'detailed_zh',
    'detailed_ug',
    'contactPerson_zh',
    'contactPerson_ug',
    'phoneNum',
    'weChat'
  ]);

  // 更新内容
  try {
    const data = await updateSecondHand(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteSecondHand(parseInt(postId, 10));
    if (data) await cornerDestroyById(parseInt(postId, 10), 6);
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;


  // 获取内容
  const post = _.pick(request.body, ['status', 'remark_zh', 'remark_ug']);

  // 执行
  try {
    let secondHand = await getIdSecondHand(postId);
    const data = await secondHandStatusChange(parseInt(postId, 10), post);
    if (data) {
      let notice = {
        type: 2,
        target_id: postId,
        target_type: 6,
        content_ug: post.remark_ug,
        content_zh: post.remark_zh,
        status: 0
      }
      // await createNotification(notice, secondHand.user_id)
    }
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/secondHand/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })
    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const carData = await updateSecondHand(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(data)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 要提供的图像尺寸
    const { size } = request.query;

    // 文件名与目录
    let filename = file[0].filename;
    let root = 'uploads/secondHand/resized';
    let resized = 'resized';

    if (size) {
      // 可用的图像尺寸
      const imageSize = ['lerge', 'medium', 'thumbnail'];

      // 检查文件尺寸是否可用
      if (!imageSize.some(item => item == size)) {
        throw new Error('FILE_NOT_FOUND');
      }

      // 检查文件是否存在
      const fileExist = fs.existsSync(
        path.join(root, resized, `${filename}-${size}`),
      )

      // 设备文件名与目录
      if (fileExist) {
        filename = `${filename}-${size}`;
        root = path.join(root, resized);
      }
    }

    // 做出响应
    response.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file[0].mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })

}
